package com.suitsoft.ut.web.dabian;

import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.utils.web.struts2.Struts2Utils;
import org.springside.modules.web.struts2.annotations.Token;

import com.google.common.collect.Lists;
import com.suitsoft.ut.commons.Constants;
import com.suitsoft.ut.commons.LogAnnotation;
import com.suitsoft.ut.commons.UserHolder;
import com.suitsoft.ut.entity.base.Student;
import com.suitsoft.ut.entity.base.Teacher;
import com.suitsoft.ut.entity.base.Team;
import com.suitsoft.ut.entity.commons.UploadFileInfo;
import com.suitsoft.ut.entity.system.SystemInfo;
import com.suitsoft.ut.entity.thesis.Thesis;
import com.suitsoft.ut.entity.thesis.ThesisFile;
import com.suitsoft.ut.entity.thesis.ThesisScore;
import com.suitsoft.ut.service.account.SystemInfoManager;
import com.suitsoft.ut.service.commons.ScoreManager;
import com.suitsoft.ut.service.commons.UploadFileManager;
import com.suitsoft.ut.service.thesis.ThesisFileManager;
import com.suitsoft.ut.util.upload.UploaderDBUtil;
import com.suitsoft.ut.util.upload.XdbFiles;
import com.suitsoft.ut.web.CrudActionSupport;
import com.suitsoft.ut.web.InitListActionSupport;

/**
 * 现场评分
 *@author Suineg
 */
@Results({@Result(name=CrudActionSupport.RELOAD,location="scene-score",type="redirect")})
public class SceneScoreAction extends InitListActionSupport{
	/**
	 * 
	 */
	private static final long serialVersionUID = -704559237216942766L;
	/** 日志输出对象 */
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	
	/** 评分 */
	private final String SCORE = "score";
	/**  */
	private final String VIEW_UPLOAD = "view-upload";
	
	/** 评分管理  */
	private ScoreManager scoreManager;
	/** 系统参数信息 管理  */
	private SystemInfoManager systeminfoManager;
	/** 流程管理  */
	private ThesisFileManager fileManager;
	/***/
	private UploadFileManager uploadFileManager;
	
	
	/** 教师实体 */
	private Teacher teacher;
	private List<SystemInfo> pingfenyiju;
	/** 收集页面的值  Map<Id,分>   id是指sytemInfo的ID */
	private Map<Long,Double> valueMap = new HashMap<Long,Double>();
	/** 文件ID */
	private Long fid;
	/** 上传文件列表 */
	private List<XdbFiles> xdbFiles = Lists.newArrayList();
	/** 已上传文件集合 */
	private List<UploadFileInfo> uploadList = Lists.newArrayList();
	
	@Override
	public String execute() throws Exception {
		teacher = teacherManger.findTeacherByUser(UserHolder.getLoginUser().getId());
		if(teacher == null){
			addActionMessage("请使用教师账号!");
			return SUCCESS;
		}
		List<Team> groups = teacher.getTeamList();
		List<Student> students = Lists.newArrayList();
		for(Team t : groups){
//			students.addAll(t.getStudents());
			for(Student st : t.getStudents()){
				thesis = st.getThesis();
				if(thesis == null){
					continue;
				}
				thesisFile = thesis.getThesisFile();
				if(thesisFile.getIsConfirmDabianAddress() == null ||!thesisFile.getIsConfirmDabianAddress().equals(1L)){
					addActionMessage("有未确定答辩时间及地点的团队");
					return SUCCESS;
				}
				if(!thesisFile.getThesisStatus().equals(Constants.THSIS_STAUTS_DABIAN_PINGYUE_TEACHER_READ_THESIS_AND_FRACTON)){
					continue;
				}
				students.add(st);
			}
		}
		Struts2Utils.getRequest().setAttribute("stduents", students);
		return SUCCESS;
	}
	/**
	 * 初始化评分页面
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String score(){
		if(id == null || id == 0l){
			addActionMessage("非法操作！");
			return RELOAD;
		}
		initList();
		thesis = thesisManager.get(id);
		loginTeacher = teacherManger.findTeacherByUser(UserHolder.getLoginUser().getId());
		pingfenyiju = Lists.newArrayList(systemCategorys.getSystemParams().get(Constants.SYSTEM_CATEGORY_PK_DABIAN_PINGFENYIJU).getSystemInfo());
		Collections.sort(pingfenyiju, new Comparator() {
			@Override
			public int compare(Object o1, Object o2) {
				SystemInfo s1 = (SystemInfo)o1;
				SystemInfo s2 = (SystemInfo)o2;
				return s1.getPmcd().compareTo(s2.getPmcd());
			}
		});
		for(ThesisScore ts : thesis.getThesisScore()){
			valueMap.put(ts.getSystemInfo().getId(), ts.getScore());
		}
		return SCORE;
	}
	
	/**
	 * 
	 * @return
	 */
	@Token
	@LogAnnotation(log = "指导教师评阅论文并评分 - 保存评分")
	public String save(){
		if(id == null || id == 0l){
			addActionMessage("非法操作");
			return RELOAD;
		}
		logger.info(valueMap.toString());
		if(valueMap.isEmpty()){
			addActionMessage("非法操作");
			return RELOAD;
		}
		try {
			thesis = thesisManager.get(id);
			List<ThesisScore> scores = Lists.newArrayList();
			for(ThesisScore s : thesis.getThesisScore()){
				if(s.getType().equals(Constants.SCORE_TYPE_DABIAN)){
					scores.add(s);
				}
			}
			//判断是否已经有评分数据了。
			//如果有 就修改
			//否则 新加
			ThesisScore score = null;
			SystemInfo systemInfo = null;
			double sumScore = 0.0;
			if(scores.size() <= 0){
				for(Long id : valueMap.keySet()){
					score = new ThesisScore();
					systemInfo = systeminfoManager.get(id);
					
					score.setThesis(thesis);
					score.setSystemInfo(systemInfo);
					//设置为指导都是
					score.setType(Constants.SCORE_TYPE_DABIAN);
					score.setScore(valueMap.get(id).doubleValue());
					score.setTeacherDate(new Date());
					score.setTeacherName(teacherManger.findTeacherByUser(UserHolder.getLoginUser().getId()).getTeacherName());
					sumScore += valueMap.get(id).doubleValue();
					scoreManager.save(score);
				}
			}else{
				for(ThesisScore ts : scores){
					double scroe = 0.0;
					scroe = valueMap.get(ts.getSystemInfo().getId());
					if(scroe == 0.0){
						addActionMessage("数据不正确！分数不能为空！");
						return RELOAD;
					}
					ts.setScore(scroe);
					ts.setTeacherDate(new Date());
					ts.setTeacherName(teacherManger.findTeacherByUser(UserHolder.getLoginUser().getId()).getTeacherName());
					scoreManager.save(ts);
					
					sumScore += scroe;
				}
			}
			thesis.setDabianScore(sumScore);
			thesisManager.save(thesis);
			
			
			String name = teacherManger.findTeacherByUser(UserHolder.getLoginUser().getId()).getTeacherName();
			Date date = new Date();
			String content = thesisFile.getDabianSceneContent();
			
			thesisFile = thesis.getThesisFile();
			thesisFile.setThesisStatus(Constants.THSIS_STAUTS_DABIAN_XIANCHANGG_DABIAN_AND_FRACTION);
			thesisFile.setDabianSceneContent(content);
			thesisFile.setDabianSceneDate(date);
			thesisFile.setDabianSceneName(name);
			fileManager.save(thesisFile);
			addActionMessage("操作成功");
		} catch (Exception e) {
			e.printStackTrace();
			addActionMessage("操作失败");
		}
		return RELOAD;
	}
	/**
	 * 下载
	 * @return
	 */
	public String download(){
		if(fid == null || fid == 0l){
			addActionMessage("非法操作");
			return SUCCESS;
		}
	//	UploaderDBUtil dbUtil = new UploaderDBUtil(ServletActionContext.getServletContext());
	//	XdbFiles files = dbUtil.getFileInfByFid(Integer.valueOf(fid.toString()));
		UploadFileInfo files = uploadFileManager.get(fid);
		try {
			Struts2Utils.getRequest().setAttribute("exportFilePath", files.getFilePathLocal());
			Struts2Utils.getRequest().setAttribute("exportFileName", files.getFileNameRemote());
			Struts2Utils.getRequest().getRequestDispatcher("/download.jsp").forward(Struts2Utils.getRequest(), Struts2Utils.getResponse());
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 查看
	 * @return
	 */
	public String view(){
		if(id == null || id == 0l){
			addActionMessage("非法操作");
		}
	//	UploaderDBUtil dbUtil = new UploaderDBUtil(ServletActionContext.getServletContext());
	//	xdbFiles = dbUtil.getFilesByUid(id.toString(),UploaderDBUtil.DABIAN);
		thesis = thesisManager.get(id);
		uploadList = thesis.getDaBianFile();
		return VIEW_UPLOAD;
	}
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public Thesis getThesis() {
		return thesis;
	}
	public void setThesis(Thesis thesis) {
		this.thesis = thesis;
	}
	public ThesisFile getThesisFile() {
		return thesisFile;
	}
	public void setThesisFile(ThesisFile thesisFile) {
		this.thesisFile = thesisFile;
	}
	public Teacher getTeacher() {
		return teacher;
	}
	public void setTeacher(Teacher teacher) {
		this.teacher = teacher;
	}
	public List<SystemInfo> getPingfenyiju() {
		return pingfenyiju;
	}
	public void setPingfenyiju(List<SystemInfo> pingfenyiju) {
		this.pingfenyiju = pingfenyiju;
	}
	public Map<Long, Double> getValueMap() {
		return valueMap;
	}
	public void setValueMap(Map<Long, Double> valueMap) {
		this.valueMap = valueMap;
	}
	@Autowired
	public void setScoreManager(ScoreManager scoreManager) {
		this.scoreManager = scoreManager;
	}
	@Autowired
	public void setSysteminfoManager(SystemInfoManager systeminfoManager) {
		this.systeminfoManager = systeminfoManager;
	}
	@Autowired
	public void setFileManager(ThesisFileManager fileManager) {
		this.fileManager = fileManager;
	}
	public Long getFid() {
		return fid;
	}
	public void setFid(Long fid) {
		this.fid = fid;
	}
	public List<XdbFiles> getXdbFiles() {
		return xdbFiles;
	}
	public void setXdbFiles(List<XdbFiles> xdbFiles) {
		this.xdbFiles = xdbFiles;
	}
	public List<UploadFileInfo> getUploadList() {
		return uploadList;
	}
	public void setUploadList(List<UploadFileInfo> uploadList) {
		this.uploadList = uploadList;
	}
	@Autowired
	public void setUploadFileManager(UploadFileManager uploadFileManager) {
		this.uploadFileManager = uploadFileManager;
	}
	
	
}

